package com.zf.yichat.controller.sys;



import com.zf.yichat.controller.BaseController;
import com.zf.yichat.model.SysMenu;
import com.zf.yichat.service.SysMenuService;
import com.zf.yichat.service.SysUserService;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.hibernate.validator.internal.util.Contracts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * @author fengsong
 */
@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysMenuService menuService;



    @RequestMapping("/index")
    public String index() {
        return "sys/menu/index";
    }

    @RequestMapping("/list")
    @ResponseBody
    public FsResponse list(Integer page, Integer limit) {

        return menuService.selectIndexList(FsPage.init(page, limit));
    }

    @RequestMapping("save/index")
    public String saveIndex(Integer id) {
        getRequest().setAttribute("menuMap", DtoChangeUtils.getMap(menuService.selectParent(),
                SysMenu::getName, SysMenu::getId
        ));

        getRequest().setAttribute("menu", Objects.nonNull(id) ? menuService.selectById(id) : null);

        return "sys/menu/save";
    }

    @RequestMapping("save")
    @ResponseBody
    public FsResponse save(SysMenu menu) {

        Contracts.assertTrue(Objects.nonNull(menu.getId()) || Objects.isNull(menuService.selectByName(menu.getName())), "用户名已存在");

        return FsResponseGen.gen(menuService.save(menu) == 1);
    }


}
